<?php
declare(strict_types=1);

namespace App\Service;

use Spiral\Prototype\Traits\PrototypeTrait;

class MemoryPostService implements PostService
{
    use PrototypeTrait;

    /**
     * @var array $data 文章数据
     */
    protected $data = [];

    public function __construct()
    {
        $this->data = $this->initPosts();
    }

    /**
     * @inheritDoc
     */
    public function getPosts(int $page = 1, int $size = 10): array
    {
        $offset = $size * ($page - 1);
        $offset = $offset < 0 ? 0 : $offset;
        $size = $size < 1 ? 1 : $size;
        $pages = floor(count($this->data) / $size) + 1;
        return [
            'pages' => $pages,
            'posts' => array_merge(array_slice($this->data, $offset, $size))
        ];
    }

    /**
     * @inheritDoc
     */
    public function getPost(int $id): ?array
    {
        $post = null;
        foreach ($this->data as $p) {
            if ( $p['id'] === $id) {
                $post = $p;
            }
        }
        return $post;
    }

    /**
     * 从 json 中读取初始文章数据
     * @return array
     */
    protected function initPosts(): array
    {
        $jsonData = $this->files->read(directory('runtime') . '/data.json');
        return json_decode($jsonData, true);
    }
}
